package cn.lmxdev.ptms.handler.exception;

import cn.lmxdev.ptms.bean.vo.ResponseVo;
import cn.lmxdev.ptms.enumeration.impl.BizHttpStateImpl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Order(3)
public class GlobalExceptionHandler {
    /* 非法参数异常处理器 */
    @ExceptionHandler(value = IllegalArgumentException.class)
    public ResponseVo<Object> illegalArgumentExceptionHandler(HttpServletRequest request, HttpServletResponse response, IllegalArgumentException e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return new ResponseVo<>(BizHttpStateImpl.NO).setMsg("参数不合法：" + e.getLocalizedMessage());
    }

    /* Http消息不可读异常处理器 */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseVo<Object> httpMessageNotReadableException(HttpServletRequest request, HttpServletResponse response, HttpMessageNotReadableException e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return new ResponseVo<>(BizHttpStateImpl.NO).setMsg("参数读取错误：" + e.getLocalizedMessage());
    }

    /* 空指针异常处理器 */
    @ExceptionHandler(value = NullPointerException.class)
    public ResponseVo<Object> exceptionHandler(HttpServletRequest request, HttpServletResponse response, NullPointerException e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return new ResponseVo<>(BizHttpStateImpl.NO).setMsg("数据空值：" + e.getLocalizedMessage());
    }

    /* 其它全部异常处理器 */
    @ExceptionHandler(value = Exception.class)
    public ResponseVo<Object> exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return new ResponseVo<>(BizHttpStateImpl.NO).setMsg("系统错误：" + e.getLocalizedMessage());
    }
}
